package com.breakfast.fun.ui.user.login;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.breakfast.fun.Constant;
import com.breakfast.fun.R;
import com.breakfast.fun.base.BaseActivity;
import com.breakfast.fun.data.entity.user.Login;
import com.breakfast.fun.event.FinishEvent;
import com.breakfast.fun.ui.home.HomeFragment;
import com.breakfast.fun.ui.user.UserFragment;
import com.breakfast.fun.util.L;
import com.breakfast.fun.util.SharedUtil;
import com.breakfast.fun.util.T;
import com.fm.openinstall.OpenInstall;
import com.fm.openinstall.listener.AppInstallListener;
import com.fm.openinstall.listener.AppWakeUpListener;
import com.fm.openinstall.model.AppData;
import com.fm.openinstall.model.Error;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;

public class RegisterActivity extends BaseActivity<RegisterPresenter, RegisterModel> implements RegisterContract.View, AppWakeUpListener, AppInstallListener {


    @Bind(R.id.iv_register_back)
    ImageView mIvRegisterBack;
    @Bind(R.id.et_register_name)
    EditText mEtRegisterName;
    @Bind(R.id.tv_register_get_code)
    TextView mTvRegisterGetCode;
    @Bind(R.id.et_register_code)
    EditText mEtRegisterCode;
    @Bind(R.id.et_register_pwd)
    EditText mEtRegisterPwd;
    @Bind(R.id.et_register_referee)
    EditText mEtRegisterReferee;
    @Bind(R.id.tv_register_birthday)
    TextView mTvRegisterBirthday;
    @Bind(R.id.ll_register)
    LinearLayout mLlRegister;
    @Bind(R.id.btn_register)
    Button mBtnRegister;
    private int time = 60;
    private Timer timer = new Timer();
    private TimerTask task;

    private String curTimeStr;
    private String codeStr = "";

    private String birthdayStr;
    private DatePickerDialog mDatePickerDialog;

    @Override
    public int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    public void initView() {
        mIvRegisterBack.setOnClickListener(v -> {
            finish();
        });

        mTvRegisterGetCode.setOnClickListener(v -> {
            if (mEtRegisterName.getText().length() != 11) {
                T.show("请检查手机格式");
                return;
            }
            presenter.getCode(mEtRegisterName.getText().toString());
        });

        if (!TextUtils.isEmpty(HomeFragment.localCode)) {
            String str;
            if (!TextUtils.isEmpty(codeStr)) {
                str = codeStr;
            } else {
                str = HomeFragment.localCode;
            }
            mEtRegisterReferee.setTextColor(Color.BLACK);
            mEtRegisterReferee.setText(str);
//            mEtRegisterReferee.setEnabled(false);
        }
        mBtnRegister.setOnClickListener(v -> {
            if (mEtRegisterName.getText().length() == 0
                    || mEtRegisterCode.getText().length() == 0
                    || mEtRegisterPwd.getText().length() == 0) {
                T.show("请检查输入是否完整");
                return;
            }

            presenter.register(mEtRegisterName.getText().toString(),
                    mEtRegisterCode.getText().toString(),
                    mEtRegisterPwd.getText().toString(),
                    mEtRegisterReferee.getText().toString(),
                    mTvRegisterBirthday.getText().toString());

        });


        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DATE);

        mDatePickerDialog = new DatePickerDialog(this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                birthdayStr = year + "-" + (month + 1) + "-" + dayOfMonth;
                mTvRegisterBirthday.setText(birthdayStr);
            }
        }, year, month - 1, day);

        mTvRegisterBirthday.setOnClickListener(v -> {
            mDatePickerDialog.show();
        });


        mEtRegisterName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s) || s.length() < 11) {
                    mTvRegisterGetCode.setBackgroundResource(R.color.gray_silver);
                    mTvRegisterGetCode.setClickable(false);
                    mEtRegisterCode.setEnabled(false);
                } else if (!TextUtils.isEmpty(s) || s.length() == 11) {
                    mTvRegisterGetCode.setBackgroundResource(R.drawable.selector_btn);
                    mTvRegisterGetCode.setClickable(true);
                    mEtRegisterCode.setEnabled(true);
                }
            }
        });
    }

    @Override
    public void sendCodeSuccess() {
        T.show("发送成功");
        new SendMessage().execute();
    }

    @Override
    public void registerSuccess(Login login) {
        T.show("注册成功");
        finish();
        Intent intent = new Intent(this, GiftActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
//        T.show("登录成功");
        SharedUtil.putString(context, "user", new Gson().toJson(login.getData()));
        SharedUtil.putString(context, "sign", login.getData().getUserSign());
        Constant.setUserSign(login.getData().getUserSign());
        Constant.setUserData(login.getData());
//        setUserAlias();
        UserFragment.isNeedRefesh = true;
        EventBus.getDefault().post(new FinishEvent("LoginActivity"));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    class SendMessage extends AsyncTask<Integer, Integer, Integer> {

        @Override
        protected Integer doInBackground(Integer... params) {

            return 1;
        }

        @Override
        protected void onPostExecute(Integer result) {
            mTvRegisterGetCode.setEnabled(false);
            mTvRegisterGetCode.setBackgroundResource(R.color.gray_silver);
            task = new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() { // UI thread
                        @Override
                        public void run() {
                            if (time <= 0) {
                                // 当倒计时小余=0时记得还原图片，可以点击
                                mTvRegisterGetCode.setEnabled(true);
                                mTvRegisterGetCode.setBackgroundResource(R.drawable.selector_btn);
                                mTvRegisterGetCode.setTextColor(Color.WHITE);
                                mTvRegisterGetCode.setText("获取验证码");
                                task.cancel();
                            } else {
                                if (mTvRegisterGetCode == null) {
                                    return;
                                }
                                mTvRegisterGetCode.setText(time + "秒后重试");
                                mTvRegisterGetCode.setTextColor(Color.rgb(125, 125, 125));
                            }
                            time--;
                        }
                    });
                }
            };

            time = 60;
            timer.schedule(task, 0, 1000);
        }
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        OpenInstall.getWakeUp(this, this);
    }

    @Override
    public void onWakeUpFinish(AppData appData, Error error) {
        if (error == null) {
            L.d("Register:OpenInstall wakeup-data : " + appData.toString());
        } else {
            L.d("Register:error : " + error.toString());
        }
    }

    @Override
    public void onInstallFinish(AppData appData, Error error) {
        if (error == null) {
            String localCode = "";
            String localData = "";
            L.d("Permission : OpenInstall install-data : " + appData.toString());
            if (!appData.getChannel().isEmpty()) {
                localCode = appData.getChannel();
                codeStr = localCode;
                //将此邀请码存入本地，在注册时候判断有没手动填写邀请码，没有则以此作为邀请码上传。
            }
            if (!appData.getData().isEmpty()) {
                localCode = appData.getData();
            }

        } else {
            L.d("Permission : error : " + error.toString());
        }
    }

    @Override
    public void finish() {
        if (task != null) {
            task.cancel();
        }
        super.finish();
    }
}
